<?php

class Admin_gamesController extends Controller{

	public $layout = false;
	public $secure = true;
	public $models = array("Admin", "Games");
	
	public function __construct() {
		parent::__construct();
	}
	
	public function index($page=1) {
		$page = $page>1 ? $page : 1;
		
		$start = ($page-1)*ITEMS_PER_PAGE;
		
		$games = $this->Games->find("*", null, false);
		
		$this->assign("games", $games);
		$this->display("admin/games/index.html");
	}
	
	public function edit($id=null) {
		$message_class = $this->session_get("message_class");
		if($message_class=="error") {
			$data = $this->session_get("form_data");
			$this->assign("games",$data);
		}else if($id) {
			$game = $this->Games->findRow("*", array("id"=>$id));
			$this->assign("game",$game);
		}
		
		$this->display("admin/games/edit.html");
		$this->session_set("message","");
		$this->session_set("message_class","");
		$this->session_set("form_data",array());
	}
	
	public function save($id = null) {
		$message = "Igra je sačuvana";
		$ok = true;
		if(!strlen($this->data["name"])) {
			$ok = false;
			$message = "Morate popuniti ime igre.";
		}
		
		if($ok) {
			if($id>0) {
				$status = $this->Games->update($this->data, array("id"=>$id));
				if(!$status) {
					$message = $this->Games->getErrorMessage();
				}
			}else{
				$id = $this->Games->insert($this->data);
				if(!$id) {
					$message = $this->Games->getErrorMessage();
				}
			}
		}
		$this->session_set("message", $message);
		$this->session_set("message_class", $ok?"ok":"error");
		$this->session_set("form_data", $ok?array():$this->data);
		
		redirect("/admin#games/edit/$id");
	}
	
	public function delete($id) {
		if($id) {
			$q = "DELETE FROM games WHERE id=$id LIMIT 1";
			$this->Games->_alter($q);
		}
		redirect("/admin_games");
	}
	
}

?>